//
//  JsLogListViewController.m
//  JsUtilitySdk
//
//  Created by Gikki Ares on 2022/12/21.
//

#import "JsLogListViewController.h"
#import "JsLogDetailViewController.h"

#import "JsFile.h"
#import "JsGeometryManager.h"

@implementation JsLogListViewControllerVm


@end


@interface JsLogListViewController ()<UITableViewDelegate,UITableViewDataSource>
{
	UITableView * mtv;
	NSMutableArray * marr;
}

@end

@implementation JsLogListViewController
//既然要增加vm的逻辑,那么所有的子类,都需要重新定义init方法,没有什么捷径.
- (instancetype)init {
	if(self = [super init]) {
		self.vm = [JsLogListViewControllerVm new];
	}
	return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
	self.title = @"日志列表";
	{
		mtv = [[UITableView alloc]init];
		mtv.frame = CGRectMake(0, JsGeometryManager.navigationBarBottom, JsGeometryManager.screenWidth, JsGeometryManager.screenHeight - JsGeometryManager.navigationBarBottom);
		[self.view addSubview:mtv];
		mtv.delegate = self;
		mtv.dataSource = self;
		mtv.backgroundColor = [UIColor clearColor];
	}
	{
		[self getLogFileList];
	}
//	self.edgesForExtendedLayout = UIRectEdgeNone;
//	mtv.bounces = NO;
}
- (void)viewDidLayoutSubviews {
	mtv.frame = CGRectMake(0, JsGeometryManager.navigationBarBottom, JsGeometryManager.screenWidth, JsGeometryManager.screenHeight - JsGeometryManager.navigationBarBottom);
}

- (void)getLogFileList {
	JsLogListViewControllerVm * vm = (JsLogListViewControllerVm *)self.vm;
	NSString * logDir = [vm logDirPath];
	bool ret = [[NSFileManager defaultManager] fileExistsAtPath:logDir];
	if(ret) {
		marr = [JsFile fileListInDirPath:logDir];
		[mtv reloadData];
	}
}

- (void)renderVm {
	[self getLogFileList];
	[super renderVm];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
	if(!cell) {
		cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
	}
	JsFile * file = marr[indexPath.row];
	cell.textLabel.text = file.fileName;
	cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2f KB",file.fileSize/1000.0];
		
	return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return marr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 40;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	JsFile * file = marr[indexPath.row];
	JsLogDetailViewController * vc = [JsLogDetailViewController new];
	JsViewControllerVm * vm = [JsViewControllerVm new];
	vm.backgroundColor = self.vm.backgroundColor;
	vc.vm = vm;
	vc.file = file;
	[self.navigationController pushViewController:vc animated:YES];
}


@end
